import { EditOutlined } from '@ant-design/icons';
import { TableProps } from 'antd';
import React, { useEffect, useState, useRef } from 'react';

import mcpService from '@/api/services/mcpService';
import { GetMcpServersListItem, GetCreatedMcpServersItem, AppsData } from '@/common';
import { Search, Empty, Button } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import TipsModals from '@/components/modals/TipsModals';
import Tables from '@/components/tables/tables';
import useModal from '@/hooks/use-modal/useModal';
import useTable from '@/hooks/use-table';
import useUserStore from '@/store/userStore';

import AppSelect from '../AppSelect';
import McpServiceInput from '../McpServiceInput';
import ModelDetail from '../ModelDetail';

import './style.scss';

const MCPService = () => {
  const modal = useModal('select', 'input', 'delete', 'detail');
  const [updateData, setUpdateData] = useState<GetMcpServersListItem>();
  const [detailData, setDetailData] = useState<GetMcpServersListItem>();
  const [selectApps, setSelectApps] = useState<AppsData[]>([]);
  const [isDeleteId, setIsDeleteId] = useState<string>();
  const { userInfo } = useUserStore();

  const {
    tablesValue,
    getTables,
    pagingInfo,
    handleSearchText,
    searchText,
    loading: tablesLoading,
    firstEntry,
  } = useTable<GetMcpServersListItem>(mcpService.getServersList);
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);
  const inputRef = useRef<any>(null);
  // 表格多选
  const rowSelection: TableProps<GetMcpServersListItem>['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
    getCheckboxProps: (record: GetMcpServersListItem) => ({
      disabled: !(record.createUser && userInfo.userId === record.createUser.userId),
    }),
  };
  const colums: TableProps<GetMcpServersListItem>['columns'] = [
    {
      title: '服务名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '关联应用数',
      width: 500,
      dataIndex: 'function',
      key: 'function',
      render: (_, record) => {
        return <div>{record?.apps?.length}</div>;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record) => {
        return (
          <div className="flex">
            <Button
              type="text"
              className="!pl-0"
              onClick={() => {
                onView && onView(record);
              }}
            >
              <SvgIcon icon="message-ic1" size="20" />
              查看
            </Button>
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => {
                onEdit && onEdit(record);
              }}
              disabled={!(record.createUser && userInfo.userId === record.createUser.userId)}
            >
              编辑
            </Button>
            <Button
              danger
              type="text"
              disabled={!(record.createUser && userInfo.userId === record.createUser.userId)}
              onClick={() => openDeleteModal('only', record.id)}
            >
              <SvgIcon icon="delete-icons" size={16} />
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  useEffect(() => {
    getTables();
  }, []);

  const handleSelectCancel = () => {
    setSelectApps([]);
    modal.select.close();
  };

  const handleInputClose = (value?: boolean) => {
    if (value) {
      getTables();
    }
    setUpdateData(undefined);
    modal.input.close();
  };
  const handleInputOk = (value?: GetCreatedMcpServersItem) => {
    if (value) {
      mcpService[value.id ? 'updateServers' : 'createServers'](value)
        .then((res) => {
          getTables();
        })
        .finally(() => { });
    }
    setSelectApps([]);
    setUpdateData(undefined);
    modal.input.close();
  };
  const handleUpdateModelValue = (value: any) => {
    setUpdateData(value);
    setSelectApps(value.apps);
    modal.select.open();
  };

  const onChange: TableProps<GetMcpServersListItem>['onChange'] = (_) => {
    getTables({ ...pagingInfo, page: 1 });
  };

  const onView = (record: GetMcpServersListItem) => {
    setDetailData(record);
    modal.detail.open();
  };

  const onEdit = (record: GetMcpServersListItem) => {
    setUpdateData(record);
    modal.input.open();
  };

  const openDeleteModal = (type?: string, id?: string) => {
    modal.delete.open();
    if (type === 'only') {
      // setTableSelectEdRows([id]);
      setIsDeleteId(id as string);
    }
  };

  const onDeleteModel = () => {
    modal.delete.startLoading();
    mcpService
      .deleteServers(isDeleteId ? [isDeleteId] : (tableSelectEdRows as string[]))
      .then((res) => {
        getTables();
        modal.delete.close();
        setTableSelectEdRows([]);
        setIsDeleteId('');
      })
      .finally(() => {
        modal.delete.stopLoading();
      });
  };

  const handleUpdateModel = (value: GetCreatedMcpServersItem[]) => {
    setUpdateData({
      ...updateData,
      apps: value,
    });
    modal.select.close();
  };

  return (
    <div className="flex flex-1 flex-col rounded-md bg-[#FFFFFFCC] ">
      <div className="flex items-center justify-between">
        <div className="w-[240px]">
          <Search
            placeholder="搜索"
            value={searchText}
            onChange={(e) => handleSearchText(e.target.value)}
          />
        </div>
        <div className="flex items-center gap-2">
          {tableSelectEdRows.length > 0 && (
            <div className="ml-6 flex items-center gap-4 text-sm text-[#1D1D1D]">
              <div className="font-font-weight-400 text-text-5">
                已选择 <span className="font-font-weight-600">{tableSelectEdRows.length}</span> 项
              </div>
              <Button
                danger
                onClick={() => openDeleteModal('all')}
                style={{
                  padding: '0 12px 0px 8px',
                }}
              >
                <SvgIcon icon="delete-outlined" size={16} />
                删除
              </Button>
            </div>
          )}
          <div
            className=" flex  h-[32px] w-[128px] cursor-pointer items-center justify-center rounded-md border !border-@brand-color !text-@brand-color"
            onClick={modal.input.open}
          >
            <SvgIcon icon="message-ic13" size="15" className="mr-1" />
            创建MCP服务
          </div>
        </div>
      </div>
      <div className="mt-4 flex-1">
        {firstEntry ? (
          <CircleLoading />
        ) : tablesValue?.length > 0 ? (
          <Tables
            rowSelection={{ type: 'checkbox', ...rowSelection }}
            rowKey="id"
            columns={colums}
            dataSource={tablesValue}
            onChange={onChange}
            paginationProps={{
              pageSize: pagingInfo.page_size,
              current: pagingInfo.page,
              total: pagingInfo.total,
              onChange(page, pageSize) {
                getTables({ ...pagingInfo, page, pageSize });
              },
            }}
            loading={tablesLoading}
            className="custom-table"
          />
        ) : (
          <Empty />
        )}
      </div>

      <McpServiceInput
        modelData={updateData}
        open={modal.input.isOpen}
        onCancel={handleInputClose}
        onSubmit={handleInputOk}
        updateModel={handleUpdateModelValue}
        ref={inputRef}
      />

      <AppSelect
        title={
          <div className="flex items-center text-text-5">
            <span className="text-base font-semibold">选择应用</span>
            <span className="text-sm font-normal">(只支持工作流应用)</span>
          </div>
        }
        open={modal.select.isOpen}
        onCancel={handleSelectCancel}
        onOk={handleUpdateModel}
        isMultiSelect={2}
        selectAppList={selectApps}
      />

      <ModelDetail
        open={modal.detail.isOpen}
        onOk={modal.detail.close}
        onCancel={modal.detail.close}
        value={detailData}
      />

      <TipsModals
        open={modal.delete.isOpen}
        onOk={onDeleteModel}
        confirmLoading={modal.delete.isLoading}
        onCancel={modal.delete.close}
        title={
          <div className="flex items-center">
            <SvgIcon icon="warning" size={20} color="#F08332" />
            <div className="ml-[10px] text-base font-bold text-[#1D2129]">删除提示</div>
          </div>
        }
      >
        <div>删除该MCP服务，会影响已使用的MCP客户端，确认删除？</div>
      </TipsModals>
    </div>
  );
};

export default MCPService;
